#!/usr/bin/env python
#coding=utf-8
import urllib2, re, sys, urlparse

def generateurl(a, c, p, s):
    # htmurl="http://www.narutodm.com/manhua/comic/"+ComicID+"/"+ComicListUrl+"/?s="+ServerList
    htmurl = "http://dm3.cococomic.com/cococomic.htm?a=%s&c=%s&p=%s&s=%s" % (a, c, p, s)
    
    return htmurl

def getchapter(url,name="unamed",mylog=None):
    "parser html source to generate chapterlist"
    '''format: <a class=link01 style='cursor:hand' OnClick="javascript:ComicListShow('171','20247','4');return false;">网球王子act.321</a>
    <a class=clink href="+server+"/cococomic.htm?a=3483&c=33383&p=1&s=1 target=_blank><img src=/images/c.gif border=0 hspace=5>南家三姊妹 act_108-111</a></div>
    '''
    # cptre = re.compile(r'OnClick="javascript:ComicListShow\(\'(\d+?)\',\'(\d+?)\',\'(\d+?)\'\);return false;">(.+?)</a>')
    cptre = re.compile(r'<a class=clink href="+server+"/cococomic.htm?a=(\d+?)&c=(\d+?)&p=(\d+?)&s=(\d+?) target=_blank><img src=/images/c.gif border=0 hspace=5>(.*?)</a>')
    chapterlist = []
    content = ''
    try:
        content = urllib2.urlopen(url).read()
        print 'content', content
        if content:
            for item in cptre.findall(content):
                title = item[4].decode('gbk').encode('utf-8')
                chapterlist.append([generateurl(item[0],item[1],item[2],item[3]),title])
        return chapterlist
    except  Exception, e:
        if mylog:
            mylog.writeLog(str(e)+'in getchapter','error')
        return None
